<template>
  <div>
    <!-- 条件查询 -->
    <el-form
      ref="searchMap"
      :inline="true"
      :model="searchMap"
      style="margin-top: 20px"
    >
      <el-form-item>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
      <!-- 姓名 -->
      <el-form-item prop="name">
        <el-input
          v-model="searchMap.name"
          placeholder="姓名"
          style="width: 200px"
        ></el-input>
      </el-form-item>

      <!-- 学校名称 -->
      <el-form-item prop="schid">
        <el-select
          v-model="searchMap.schid"
          placeholder="学校名称"
          style="width: 110px"
        >
          <el-option
            v-for="item in schools"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <!-- <el-button type="primary" >新增</el-button> -->
        <el-button type="primary" @click="submitForm('searchMap')"
          >搜索</el-button
        >
        <el-button type="default" @click="resetForm('searchMap')">重置</el-button>
        <el-button type="danger" @click="softDeleteStudent">删除选中</el-button>
        <el-button type="default" @click="exportExcel">导出到excel</el-button>
        <el-button type="success" @click="resetForm('searchMap')">批量添加</el-button>
      </el-form-item>
    </el-form>

    <br />

    <br />
    <!-- 分页 -->
    <el-table
      :data="list"
      ref="multipleTable"
      height="480"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      tooltip-effect="dark"
      stripe
      highlight-current-row
    >
      <!-- <el-table-column prop="avatar" label="照片"  align="center">
                <template slot-scope="scope">
                    <el-image :src="scope.row.avatar" fit="scale-down" style="width:60px;height:60px;"></el-image>
                </template>
            </el-table-column> -->
    
    <el-table-column
      type="selection"
      width="55">
    </el-table-column>
      <el-table-column type="index" :index="hadleIndex"  label="序号"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="birth" label="生日"></el-table-column>
      <el-table-column prop="sch.name" label="学校姓名"></el-table-column>
      <el-table-column prop="sch.info" label="学校地址"></el-table-column>
      <el-table-column>
        <template slot-scope="scope">
          <el-button type="primary" @click="seeDetail(scope.row.id)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :page-size="pageSize"
      layout="total, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!--   查看详情 模态框  -->
    <div>
        <el-dialog
            title="提示"
            :visible.sync="detailDialogVisible"
            width="800px"
            :before-close="handleClose"
        >
        <div>
            <el-table
                :data="detailsData"
        
                border
                style="width: 100%">
                    <el-table-column
                        prop="c.code"
                        label="课程号"
                       >
                    </el-table-column>
                    <el-table-column
                    prop="c.name"
                    label="课程名称"
                   >
                    </el-table-column>
                    <el-table-column
                    prop="score"
                    label="分数">
                    </el-table-column>
            </el-table>
       </div>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="detailDialogVisible = false"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>

    <!-- ADD -->
    <div>
        <el-dialog title="学生信息添加"  :visible.sync="dialogFormVisible" width="800px">
            <el-form  ref="pojoForm" :rules="rule" label-width="120px" label-position="right" style="width: 700px;"
            :model="pojo">
                <el-form-item label="姓名" prop="name" >
                    <el-input v-model="pojo.name" ></el-input>
                </el-form-item>
                <el-form-item label="年龄" prop="age" >
                    <el-input type="number" v-model="pojo.age" ></el-input>
                </el-form-item>
                
                <!-- 学校名称 -->
                <el-form-item prop="schid">
                    <el-select
                    v-model="pojo.schid"
                    placeholder="学校名称"
                    style="width: 110px"
                    >
                    <el-option
                        v-for="item in schools"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                    </el-select>
                </el-form-item>

                <!-- 上传图片-->
                <el-form-item label="上传头像" prop="picid">
                    <!--  http://42.192.3.100:9527/sysFile/fileUpload -->
                    <el-upload action="http://localhost:8080/addPic"
                    list-type="picture-card" 
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove" :limit="1"
                    :on-success="handleAvatarSuccess"
                    :on-exceed="handleExceed" 
                    :file-list="fileList"
                    :show-file-list="true"
                    :before-upload="beforeAvatarUpload"
                    ref="addpic">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>


                <!-- <el-form-item label="主演" prop="protagonist" >
                    <el-input v-model="pojo.protagonist"></el-input>
                </el-form-item>
                <el-form-item label="制片国家/地区" prop="region">
                    <el-input v-model="pojo.region"></el-input>
                </el-form-item>
                <el-form-item label="语言" prop="language">
                    <el-input v-model="pojo.language"></el-input>
                </el-form-item> -->
                
                <el-form-item label="生日" prop="birth" >
                    <el-date-picker style="width: 200px" format="yyyy-MM-dd" value-format="yyyy-MM-dd" v-model="pojo.birth" type="date" placeholder="生日"></el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible=false">取消</el-button>
                <el-button type="primary" @click="addData('pojoForm')">提交</el-button>                
            </div>
        </el-dialog>
    </div>
  </div>
</template>

<script>
import dao from "@/api/dao";

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 5,
      total: 0,
      list: [], //分页

      searchMap: {
        //表格的每一列数据
        name: "", //姓名
        schid: null,
      },
      // 成绩 - 课程
      pojo:{
            name:'',
            age: null,
            birth: '',
            schid: null,
            picid: 1,   //图片
        },

      schools: [], // 获取到的所有学校列表
      detailDialogVisible: false, // 控制模态框显示与否 ~
      multipleSelection: [],      // 复选框 选中的项 数组
      dialogFormVisible: false,  // ADD
      fileList:[],  //上传文件列表
      dialogImageUrl: '',//上传图片地址
      dialogVisible: false, // 放大图片
      rule: {
          name: {},
          age: {},
          birth:{},
      },    // 验证

      detailsData : [],  // 查看详情 数据
      
    };
  },

  created() {
    this.fetchData();
  },

  methods: {
    fetchData() {
      this.fetchSchoolData();
      dao
        .searchAll(this.currentPage, this.pageSize, this.searchMap)
        .then((response) => {
          if (response.data.code === 2000) {
            this.list = response.data.data.rows;
            // console.log(this.list);
            this.total = response.data.data.total;
            // this.$message({
            // message:response.data.msg,
            // type:'success',
            // })
          } else {
            this.$message({
              message: response.data.msg,
              type: "warning",
            });
          }
        });
    },

    /* 异步请求获取所有学校[下拉列表] 同步到schools 数组 */
    fetchSchoolData() {
      dao.searchAllSchool().then((response) => {
        // console.log(response);
        this.schools = response.data.data;
      });
    },

    /* 查询 */
    submitForm(formName) {
      this.fetchData();
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },

    //查询重置

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //条件搜索
    submitForm(formName) {
      this.fetchData();
    },

    // 查看详情 具体方法
    seeDetail(id) {
      this.detailDialogVisible = true;
        dao.seeDetails(id)
        .then(response => {
            if(response.data.code === 2000){
               this.detailsData = response.data.data;
            }else{
                this.$message({
                message:response.data.msg,
                type:'warning',
            })
            }
        })
        .catch(error => {
            this.$message({
                message:'请求失败',
                type:'error',
            })
        })
        
    },

    // 模态框 关闭 方法
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    // 返回一个与分页匹配的 - 序号
    hadleIndex(val){
        return this.pageSize * (this.currentPage - 1) + 1 + val;
    },

    // 选中某一行~~
    toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
    // 全选 or 全不选-- 
    handleSelectionChange(val) {
        this.multipleSelection = val;
      },

    /* ADD */
    addData(formName){
        this.$refs[formName].validate((valid) => {
            if (valid){
                dao.add(this.pojo).then(response=>{
                    if(response.data.code == 2000){
                        this.$message({
                            message: response.data.msg,
                            type: 'success'
                        })
                        this.fetchData()
                        this.dialogFormVisible = false
                    }else{
                        this.$message({
                        message:response.data.msg,
                        type:'warning',
                        })
                    }
                })
            }else{
                this.$message({
                message:'填写有误！',
                type:'warning',
                })
            }
        })           
    },
    handleAdd(){
        this.dialogFormVisible = true
        this.pojo.type = []
        this.$nextTick(() => { 
            this.$refs['pojoForm'].resetFields()
            this.$refs.addpic.clearFiles()
        })
    },


    /* 上传文件 开始 */


    // 删除 回调函数
    handleRemove(file, fileList) {
        console.log(file)
    },

    /* 图片预览*/
    handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
    },
    // 上传成功 接口
    handleAvatarSuccess(response, file, fileList){
       if(response.code === 200){
           this.pojo.picid = response.data;
           alert(response.data);
           this.$message({
               type: "success",
               message: "图片上传成功"
           })
       }
    },
    handleExceed(file,fileList){
        this.$message.error('最多传递一张图片！');
    },

    beforeAvatarUpload(file){
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 / 1024 < 500;

        if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
        }
            
        if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 500KB!');
        }
        return isJPG && isLt2M;
    }, 
     
        /* 上传文件结束 */

    // Excel

     exportExcel(){
        // 创建 数组存储  所需的学生  id
        const ids = [];
        // 遍历向 复选框数据中获取~
        if(this.multipleSelection.length !== 0){
             this.multipleSelection.forEach(item => {
                ids.push(item.id);
            });
            window.location.href = "http://localhost:8080/stu?method=exportExcel&ids=" + ids          
        }else{
            alert("请至少选择一条")
        }
    },

   //  软删除 学生信息
    softDeleteStudent(){
        const ids = [];
        // 如果 有选中的-->
        if(this.multipleSelection.length !== 0){
            // 
            this.multipleSelection.forEach(item => {
                ids.push(item.id);
            });
            // 实现异步软删除
            dao.softDelete(ids + "")
            .then(response => {
                if(response.data.code === 2000){
                    this.fetchData();               // 回显数据
                    this.$message({
                        type: "success",
                        message: "删除成功"
                    })
                }
            })
        }else{
            alert("请至少选择一条")
        }
    }
    
  },
};
</script>

<style></style>
